const formidable = require("formidable");
const path = require("path");
const fs = require("fs");
const {fileRoot} = require("../../config/index");

const files = {
    /** 图片上传 **/
    img_upload : (req, res) => {
        let {img_id,img_url} = req.query;
        let date = new Date();
        let ymd = date.getFullYear()+"-"+(date.getMonth()+1)+"-"+date.getDate();
        let file_path = `${fileRoot}${path.sep}${ymd}`;
        let form = new formidable.IncomingForm();   //创建上传表单
        if(fs.existsSync(img_url.replace("/\//g",path.sep))&&img_url != ""){
            fs.unlinkSync(img_url);
        }
        if(!fs.existsSync(file_path)){
            let pathtemp;
            file_path.split(path.sep).forEach(function(dirname){
                if(pathtemp) {
                    pathtemp = path.join(pathtemp,dirname);
                } else {
                    pathtemp = dirname;
                }
                if(!fs.existsSync(pathtemp)) {
                    if(typeof fs.mkdirSync(pathtemp) != "undefined"){
                        res.json({
                            status: false,
                            error: "创建<"+pathtemp+">文件目录失败"
                        });
                        return ;
                    }

                }
            })
        }
        form.encoding = 'utf-8';		//设置编辑
        form.uploadDir = file_path;	 //设置上传目录
        form.keepExtensions = true;	 //保留后缀
        form.maxFieldsSize = 5 * 1024 * 1024;   //文件大小
        form.parse(req, (err, fields, files) => {
            if (err) {
                res.json({
                    status : false,
                    error : "上传出错"
                });
                return;
            }

            let file = files[img_id];
            let extName = '';  //后缀名
            switch (file.type) {
                case 'image/pjpeg':
                    extName = 'jpg';
                    break;
                case 'image/jpeg':
                    extName = 'jpg';
                    break;
                case 'image/png':
                    extName = 'png';
                    break;
                case 'image/x-png':
                    extName = 'png';
                    break;
            }
            let avatarName = new Date().getTime() + '.' + extName;
            let newPath = form.uploadDir + path.sep+ avatarName;
            fs.renameSync(file.path, newPath);  //重命名
            res.json({
                status : true,
                data : {
                    originName : file.name,
                    name : avatarName ,
                    path : "/"+newPath
                }
            });
        });
    },
    /** 生成html文件 **/
    html_upload : (contentUrl,content) => {
        if (contentUrl == "") {
            let date = new Date();
            let ymd = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate();
            let file_path = `${fileRoot}${path.sep}${ymd}`;
            if (!fs.existsSync(file_path)) {
                let pathtemp;
                file_path.split(path.sep).forEach(function (dirname) {
                    if (pathtemp) {
                        pathtemp = path.join(pathtemp, dirname);
                    } else {
                        pathtemp = dirname;
                    }
                    if (!fs.existsSync(pathtemp)) {
                        if (typeof fs.mkdirSync(pathtemp) != "undefined") {
                            res.json({
                                status: false,
                                error: "创建<" + pathtemp + ">文件目录失败"
                            });
                            return;
                        }

                    }
                })
            }
            contentUrl = file_path + path.sep + date.getTime() + ".html";
        }
        let info = fs.writeFileSync(contentUrl, content);
        if (typeof info == "undefined") {
            contentUrl = "/"+contentUrl.replace(/\\/g,"/");
            return contentUrl;
        }
        return "error";
    },
    /** 删除图片 **/
    img_del: (req,res) => {
        let {img_url} = req.query;
        fs.unlinkSync(img_url.replace("/\//g",path.sep));
        res.json({
            msg : "删除成功"
        });
    },
    /** 删除文件组 **/
    file_ground_del: (address) => {
        if(typeof address != "undefined" && address != "") {
            if(typeof address == "object"  ) {
                for(let value of address) {
                    if(fs.existsSync(value.replace("/\//g",path.sep).substr(1))){
                        fs.unlinkSync(value.replace("/\//g",path.sep).substr(1));
                    }
                }
            }else if(typeof address == "string") {
                if(fs.existsSync(address.replace("/\//g",path.sep).substr(1))){
                    fs.unlinkSync(address.replace("/\//g",path.sep).substr(1));
                }
            }
        }
    },
    /** 地址符转化 **/
    addressSep : (address) => {
        return address.substr(1).replace(/\//g,path.sep);
    },
    /** 读取html文件内容 **/
    read_html : (req,res) => {
        let {html_url} = req.query;
        let content = fs.readFileSync(html_url.replace("/\//g",path.sep),"utf-8");
        res.json({
            status: true,
            data: content
        });

    }
};
module.exports = files;
